﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Business.Prod;
using ESOL.Business.ProcessingService;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Fa;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Bpt;

namespace ESOL.WinUI.Manufacture
{
    public partial class frmMaintainWorkCenters : BaseForm.frmBaseDialogyMaintainForm
    {
        #region vars
        private ProdWorkcentersEntity workcenter;
        private bool modifyFlag = false;
        private List<ProdWorkcentersPersonEntity> addedPersons = new List<ProdWorkcentersPersonEntity>();
        private List<ProdWorkcentersPersonEntity> modifiedPersons = new List<ProdWorkcentersPersonEntity>();
        private List<ProdWorkcentersPersonEntity> delPersons = new List<ProdWorkcentersPersonEntity>();
        private List<ProdWorkcentersAssetsEntity> addedAssets = new List<ProdWorkcentersAssetsEntity>();
        private List<ProdWorkcentersAssetsEntity> modifiedAssets = new List<ProdWorkcentersAssetsEntity>();
        private List<ProdWorkcentersAssetsEntity> delAssets = new List<ProdWorkcentersAssetsEntity>();
        #endregion

        #region ctors
        public frmMaintainWorkCenters()
        {
            InitializeComponent();
        }
        public frmMaintainWorkCenters(ActionType thisActionType)
        {
            InitializeComponent();
            if (thisActionType == null)
                throw new Exception("初始化失败，状态为空！");
            if (thisActionType != ActionType.New)
                throw new Exception("初始化失败，状态错误！");
            this.ThisActionType = thisActionType;
        }
        public frmMaintainWorkCenters(ActionType thisActionType, ProdWorkcentersEntity m)
        {
            InitializeComponent();
            if (thisActionType == null)
                throw new Exception("初始化失败，状态为空！");
            if (m == null)
                throw new Exception("初始化失败，工作中心不存在！");
            this.ThisActionType = thisActionType;
            this.workcenter = m;
        }
        #endregion

        #region functions
        private void BindCombobox()
        {
            UICommon.UICommonFunctions.BindComboboxByEnum(cmbType, typeof(WorkCentersType), typeof(int), false);
        }

        private void BindGrid()
        {
            DataTable dtPersons = new DataTable();
            dtPersons.Columns.Add("WORKCENTERS_CODE");
            dtPersons.Columns.Add("PERSON_ID");
            dtPersons.Columns.Add("PERSON_NAME");
            dtPersons.Columns.Add("PERSON_CODE");
            gvPersons.DataSource = dtPersons;
            DataTable dtAssets = new DataTable();
            dtAssets.Columns.Add("WORKCENTERS_CODE");
            dtAssets.Columns.Add("ASSET_ID");
            dtAssets.Columns.Add("ASSET_NAME");
            dtAssets.Columns.Add("ASSET_CODE");
            gvAssets.DataSource = dtAssets;
        }

        private void SetFields(ProdWorkcentersEntity workcenter)
        {
            if (workcenter == null)
                return;
            txtName.Text = workcenter.Name;
            txtCode.Text = workcenter.Code;
            txtCode.Properties.ReadOnly = true;
            if (cmbType.DataSource != null)
            {
                cmbType.SetSelectedValue(workcenter.Type);
            }
            if (workcenter.Active == 0)
            {
                cbActive.Checked = false;
            }
            else if (workcenter.Active == 1)
            {
                cbActive.Checked = true;
            }
            txtWorkingPeriod.Text = workcenter.WorkingPeriod.ToString();

            DataTable workcenterPersons = new DataTable();
            workcenterPersons = ProdWorkcentersPersonBs.GetAllDtForCode(workcenter.Code);
            workcenterPersons.AcceptChanges();
            gvPersons.DataSource = workcenterPersons;
            DataTable workcenterAssets = new DataTable();
            workcenterAssets = ProdWorkcentersAssetsBs.GetAllDtForCode(workcenter.Code);
            workcenterAssets.AcceptChanges();
            gvAssets.DataSource = workcenterAssets;

            txtEfficiencyFactor.Text = workcenter.EfficiencyFactor.ToString();
            txtCapacityCycle.Text = workcenter.CapacityCycle.ToString();
            txtTimeCycle.Text = workcenter.TimeCycle.ToString();
            txtTimeBefore.Text = workcenter.TimeBeforeProd.ToString();
            txtTimeAfter.Text = workcenter.TimeAfterProd.ToString();
            if (string.IsNullOrEmpty(workcenter.ProductId.ToString()) == false)
            {
                MstProductEntity product = MstProductBs.GetProductByProductId(workcenter.ProductId);
                txtProduct.Text = product.ProductName;
                txtProduct.Tag = product;
            }
            txtCostHour.Text = workcenter.CostHour.ToString();
            txtCostCycle.Text = workcenter.CostCycle.ToString();
        }

        private bool CheckFields()
        {
            if (string.IsNullOrEmpty(txtName.Text))
            {
                MessageBox.Show("名称不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtName.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtCode.Text))
            {
                MessageBox.Show("代码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtCode.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtWorkingPeriod.Text))
            {
                MessageBox.Show("工作周期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtWorkingPeriod.Focus();
                return false;
            }
            if (UICommonFunctions.CheckDataGrid(gvPersons) == false)
                return false;
            if (UICommonFunctions.CheckDataGrid(gvAssets) == false)
                return false;
            return true;
        }

        private void SetEntity()
        {
            if (ThisActionType == ActionType.New)
                workcenter = new ProdWorkcentersEntity();
            ProdWorkcentersEntity temp = workcenter;
            if (workcenter.Name != txtName.Text)
                workcenter.Name = txtName.Text;
            if (workcenter.Code != txtCode.Text)
                workcenter.Code = txtCode.Text;
            workcenter.Active = (cbActive.Checked ? 1 : 0);
            workcenter.Type = (int)cmbType.SelectedValue;
            if (workcenter.WorkingPeriod.ToString() != txtWorkingPeriod.Text)
                workcenter.WorkingPeriod = Convert.ToDecimal(txtWorkingPeriod.Text);
            if (workcenter.EfficiencyFactor.ToString() != txtEfficiencyFactor.Text && !string.IsNullOrEmpty(txtEfficiencyFactor.Text))
                workcenter.EfficiencyFactor = Convert.ToDecimal(txtEfficiencyFactor.Text);
            if (workcenter.CapacityCycle.ToString() != txtCapacityCycle.Text && !string.IsNullOrEmpty(txtCapacityCycle.Text))
                workcenter.CapacityCycle = Convert.ToDecimal(txtCapacityCycle.Text);
            if (workcenter.TimeCycle.ToString() != txtTimeCycle.Text && !string.IsNullOrEmpty(txtTimeCycle.Text))
                workcenter.TimeCycle = Convert.ToDecimal(txtTimeCycle.Text);
            if (workcenter.TimeBeforeProd.ToString() != txtTimeBefore.Text && !string.IsNullOrEmpty(txtTimeBefore.Text))
                workcenter.TimeBeforeProd = Convert.ToDecimal(txtTimeBefore.Text);
            if (workcenter.TimeAfterProd.ToString() != txtTimeAfter.Text && !string.IsNullOrEmpty(txtTimeAfter.Text))
                workcenter.TimeAfterProd = Convert.ToDecimal(txtTimeAfter.Text);
            if (txtProduct.Tag != null)
            {
                if (workcenter.ProductId != ((MstProductEntity)txtProduct.Tag).ProductId)
                {
                    workcenter.ProductId = ((MstProductEntity)txtProduct.Tag).ProductId;
                }
            }
            if (workcenter.CostHour.ToString() != txtCostHour.Text && !string.IsNullOrEmpty(txtCostHour.Text))
                workcenter.CostHour = Convert.ToDecimal(txtCostHour.Text);
            if (workcenter.CostCycle.ToString() != txtCostCycle.Text && !string.IsNullOrEmpty(txtCostCycle.Text))
                workcenter.CostCycle = Convert.ToDecimal(txtCostCycle.Text);
            if (workcenter != temp)
                modifyFlag = true;
        }

        private bool Save()
        {
            if (CheckFields() == false)
                return false;
            SetEntity();
            if (ThisActionType == ActionType.New)
            {
                DataTable dt = gvPersons.DataSource as DataTable;
                foreach (DataRow dr in dt.Rows)
                {
                    ProdWorkcentersPersonEntity m = new ProdWorkcentersPersonEntity(dr);
                    addedPersons.Add(m);
                }
                DataTable dt2 = gvAssets.DataSource as DataTable;
                foreach (DataRow dr in dt2.Rows)
                {
                    ProdWorkcentersAssetsEntity m = new ProdWorkcentersAssetsEntity(dr);
                    addedAssets.Add(m);
                }
                if (WorkCenterService.Insert(workcenter, addedPersons, addedAssets))
                    MessageBox.Show("新增成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            else if (ThisActionType == ActionType.Modify)
            {
                DataTable dt = gvPersons.DataSource as DataTable;
                foreach (DataRow dr in dt.Rows)
                {
                    switch (dr.RowState)
                    {
                        case DataRowState.Added:
                            ProdWorkcentersPersonEntity add = new ProdWorkcentersPersonEntity(dr);
                            addedPersons.Add(add);
                            break;
                        case DataRowState.Modified:
                            ProdWorkcentersPersonEntity modified = new ProdWorkcentersPersonEntity(dr);
                            modifiedPersons.Add(modified);
                            break;
                    }
                }
                DataTable dt2 = gvAssets.DataSource as DataTable;
                foreach (DataRow dr in dt2.Rows)
                {
                    switch (dr.RowState)
                    {
                        case DataRowState.Added:
                            ProdWorkcentersAssetsEntity add = new ProdWorkcentersAssetsEntity(dr);
                            addedAssets.Add(add);
                            break;
                        case DataRowState.Modified:
                            ProdWorkcentersAssetsEntity modified = new ProdWorkcentersAssetsEntity(dr);
                            addedAssets.Add(modified);
                            break;
                    }
                }
                if (WorkCenterService.Update(workcenter, addedPersons, modifiedPersons, delPersons, addedAssets, modifiedAssets, delAssets))
                    MessageBox.Show("修改成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            return true;
        }
        #endregion

        #region events
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindCombobox();
            BindGrid();
            if (ThisActionType == ActionType.Modify || ThisActionType == ActionType.View)
            {
                SetFields(workcenter);
            }
        }

        protected override void Click_Save()
        {
            if (Save())
                this.DialogResult = DialogResult.OK;
        }

        private void txtProduct_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                txtProduct.Tag = frm.SelectedProduct;
                txtProduct.Text = frm.SelectedProduct.ProductName;
            }
            else
            {
                txtProduct.Tag = null;
                txtProduct.Text = "";
            }
        }

        private void tsmNewPerson_Click(object sender, EventArgs e)
        {
            DataTable dt = gvPersons.DataSource as DataTable;
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
        }

        private void tsmDelPerson_Click(object sender, EventArgs e)
        {
            DataRow dr = gridView1.GetFocusedDataRow();
            if (dr.RowState == DataRowState.Unchanged)
            {
                ProdWorkcentersPersonEntity m = new ProdWorkcentersPersonEntity(dr);
                delPersons.Add(m);
            }
            DataTable dt = gvPersons.DataSource as DataTable;
            dt.Rows.Remove(dr);
        }

        private void tsmNewAsset_Click(object sender, EventArgs e)
        {
            DataTable dt = gvAssets.DataSource as DataTable;
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
        }

        private void tsmDelAsset_Click(object sender, EventArgs e)
        {
            DataRow dr = gridView2.GetFocusedDataRow();
            if (dr.RowState == DataRowState.Unchanged)
            {
                ProdWorkcentersAssetsEntity m = new ProdWorkcentersAssetsEntity(dr);
                delAssets.Add(m);
            }
            DataTable dt = gvAssets.DataSource as DataTable;
            dt.Rows.Remove(dr);
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DataRow dr = gridView1.GetFocusedDataRow();
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                dr["PERSON_ID"] = frm.SelectedPerson.PersonId;
                dr["PERSON_NAME"] = frm.SelectedPerson.NameCn;
                dr["PERSON_CODE"] = frm.SelectedPerson.PersonCode;

            }
        }

        private void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DataRow dr = gridView2.GetFocusedDataRow();
            frmMaintainAssetQuery frm = new frmMaintainAssetQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedAsset != null)
            {
                dr["ASSET_ID"] = frm.SelectedAsset.AssetId;
                dr["ASSET_NAME"] = frm.SelectedAsset.AssetName;
                dr["ASSET_CODE"] = frm.SelectedAsset.AssetCode;

            }
        }

        #endregion


    }
}
